package org.jeecg.modules.assets.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.assets.dto.ApplyEditBeachDto;
import org.jeecg.modules.assets.entity.AssetsApplyDept;
import org.jeecg.modules.assets.entity.AssetsApplyItem;
import org.jeecg.modules.assets.entity.AssetsCategory;
import org.jeecg.modules.assets.entity.AssetsItem;
import org.jeecg.modules.assets.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 设备申领单管理
 * @Author: jeecg-boot
 * @Date: 2024-11-09
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "设备申领单管理")
@RestController
@RequestMapping("/assets/assetsApplyItem")
public class AssetsApplyItemController extends JeecgController<AssetsApplyItem, IAssetsApplyItemService> {
    @Autowired
    private IAssetsApplyItemService assetsApplyItemService;
    @Autowired
    private IAssetsCategoryService assetsCategoryService;
    @Autowired
    private IAssetsApplyDeptService assetsApplyDeptService;
    @Autowired
    private IAssetsItemService assetsItemService;


    /**
     * 分页列表查询
     *
     * @param assetsApplyItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "设备申领单管理-分页列表查询")
    @ApiOperation(value = "设备申领单管理-分页列表查询", notes = "设备申领单管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AssetsApplyItem assetsApplyItem,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String deviceCode = assetsApplyItem.getDeviceCode();
        assetsApplyItem.setDeviceCode(null);

        QueryWrapper<AssetsApplyItem> queryWrapper = QueryGenerator.initQueryWrapper(assetsApplyItem, req.getParameterMap());
        Page<AssetsApplyItem> page = new Page<AssetsApplyItem>(pageNo, pageSize);
        //设备编码不为空
        if (StringUtils.isNotEmpty(deviceCode) && !deviceCode.equals("null")) {
            queryWrapper.like("device_code", deviceCode);
        }

        //如果开始时间不为空
        if (assetsApplyItem.getStartTime() != null) {
            queryWrapper.ge("apply_date", assetsApplyItem.getStartTime());
        }
        if (assetsApplyItem.getEndTime() != null) {
            queryWrapper.le("apply_date", assetsApplyItem.getEndTime());
        }

        //根据申领日期倒序
        queryWrapper.orderByDesc("apply_date");
        IPage<AssetsApplyItem> pageList = assetsApplyItemService.page(page, queryWrapper);
        List<AssetsApplyItem> records = pageList.getRecords();
        for (AssetsApplyItem record : records) {
            //判断分类
            if (record.getCategory() != null) {
                AssetsCategory byId = assetsCategoryService.getById(record.getCategory());
                if (byId != null) {

                    record.setAssetCoding(byId.getAlias()!=null?byId.getAlias()+record.getAssetCoding():record.getAssetCoding());
                }
            }
        }

        return Result.OK(pageList);
    }


    /**
     * 添加
     *
     *
     * @param assetsApplyItem
     * @return
     */
    @AutoLog(value = "设备申领单管理-添加")
    @ApiOperation(value = "设备申领单管理-添加", notes = "设备申领单管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AssetsApplyItem assetsApplyItem) {
        assetsApplyItemService.saveApply(assetsApplyItem);
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param assetsApplyItem
     * @return
     */
    @AutoLog(value = "设备申领单管理-批量添加")
    @ApiOperation(value = "设备申领单管理-批量添加", notes = "设备申领单管理-批量添加")
    @PostMapping(value = "/beachAdd")
    public Result<?> add(@RequestBody List<AssetsApplyItem> assetsApplyItem) {
        for (AssetsApplyItem applyItem : assetsApplyItem) {
            assetsApplyItemService.saveApply(applyItem);
        }

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param assetsApplyItem
     * @return
     */
    @AutoLog(value = "设备申领单管理-编辑")
    @ApiOperation(value = "设备申领单管理-编辑", notes = "设备申领单管理-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody AssetsApplyItem assetsApplyItem) {
        //如果申请单已经归还，则不允许修改
        if (Objects.equals(assetsApplyItem.getApplyStatus(),"2")) {
            return Result.error("该申领单已经归还，不允许修改！");
        }

        AssetsApplyItem byId = assetsApplyItemService.getById(assetsApplyItem.getId());
        //判断申领单为是否变更
        if (!Objects.equals(assetsApplyItem.getDeptId(),byId.getDeptId()))

        {
            //变更原始数据
            if (assetsApplyItem.getDeptId()!=null) {
            }
            if (assetsApplyItem.getDeptId()!=null) {
                AssetsApplyDept aftef = assetsApplyDeptService.getById(assetsApplyItem.getDeptId());
                aftef.setNum((aftef.getNum()==null?1:aftef.getNum()) +1);
                AssetsItem byId1 = assetsItemService.getById(assetsApplyItem.getAssetsId());
                byId1.setDeptId(assetsApplyItem.getDeptId());
                byId1.setDeptName(aftef.getDeptName());
                assetsItemService.updateById(byId1);
                //获取设备
            }
            if (byId.getDeptId()!=null) {
                AssetsApplyDept befare = assetsApplyDeptService.getById(byId.getDeptId());
                befare.setNum((befare.getNum()==null?1:befare.getNum()) + 1);

                //获取设备
            }
            //将原数据修改为借后单位

        }


        assetsApplyItemService.updateById(assetsApplyItem);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param assetsApplyItem
     * @return
     */
    @AutoLog(value = "设备申领单管理-批量编辑")
    @ApiOperation(value = "设备申领单管理-批量编辑", notes = "设备申领单管理-批量编辑")
    @RequestMapping(value = "/beacheEdit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody ApplyEditBeachDto assetsApplyItem) {
        String[] ids = assetsApplyItem.getIds().split(",");
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.in("id", ids);
        wrapper.set("remark", assetsApplyItem.getRemark());
        wrapper.set("lender", assetsApplyItem.getLender());
        wrapper.set("dept_id", assetsApplyItem.getDeptId());
        wrapper.set("dept_name", assetsApplyItem.getDeptName());
        //todo
        assetsApplyItemService.update(wrapper);
        for (String id : ids) {
            AssetsApplyItem byId = assetsApplyItemService.getById(id);
            //判断申领单为是否变更
            if (!Objects.equals(assetsApplyItem.getDeptId(),byId.getDeptId())) {
                //变更原始数据
                if (assetsApplyItem.getDeptId() != null) {
                    AssetsApplyDept aftef = assetsApplyDeptService.getById(assetsApplyItem.getDeptId());
                    aftef.setNum((aftef.getNum() == null ? 1 : aftef.getNum()) + 1);
                    AssetsItem byId1 = assetsItemService.getById(id);
                    byId1.setDeptId(assetsApplyItem.getDeptId());
                    byId1.setDeptName(aftef.getDeptName());
                    assetsItemService.updateById(byId1);
                    //获取设备
                }
                if (byId.getDeptId() != null) {
                    AssetsApplyDept befare = assetsApplyDeptService.getById(byId.getDeptId());
                    befare.setNum((befare.getNum() == null ? 1 : befare.getNum()) + 1);

                }
            }
        }


        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备申领单管理-通过id删除")
    @ApiOperation(value = "设备申领单管理-通过id删除", notes = "设备申领单管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        assetsApplyItemService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "设备申领单管理-批量删除")
    @ApiOperation(value = "设备申领单管理-批量删除", notes = "设备申领单管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.assetsApplyItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备申领单管理-通过id查询")
    @ApiOperation(value = "设备申领单管理-通过id查询", notes = "设备申领单管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AssetsApplyItem assetsApplyItem = assetsApplyItemService.getById(id);
        return Result.OK(assetsApplyItem);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param assetsApplyItem
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AssetsApplyItem assetsApplyItem) {
        return super.exportXls(request, assetsApplyItem, AssetsApplyItem.class, "设备申领记录");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "设备申领单管理-导入", notes = "设备申领单管理-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        String msg = assetsApplyItemService.importExcel(request, response);
        return Result.OK(msg);
    }
    /**
     *设备明细导入。存在更新，不存新增
     */

}
